package com.alpha.consumer.service;

import com.alibaba.fastjson.JSON;
import com.alpha.consumer.client.StudentServerFeign;
import com.alpha.consumer.mapper.CustomerDao;
import com.alpha.consumer.pojo.Customer;
import com.alpha.consumer.pojo.Student;
import com.alpha.consumer.util.RedisUtil;
import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author YDF
 * @version 1.0.0
 * @Description 调用方
 * @createTime 2020年08月19日 14:38:00
 */
@Service
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private StudentServerFeign studentServerFeign;
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public int deleteByPrimaryKey(Integer id) {
		return customerDao.deleteByPrimaryKey(id);
	}
	
	@Override
	public int insert(Customer record) {
		return customerDao.insert(record);
	}
	
	@LcnTransaction(propagation = DTXPropagation.REQUIRED) //分布式事务注解(调用方)
	@Transactional(rollbackFor = Exception.class) //本地事务注解
	@Override
	public int insertSelective(Customer record) {
//		Student student = Student.builder()
//				.name(record.getName())
//				.mobile(record.getMobile())
//				.age(record.getAge())
//				.build();
		Student student = new Student();
		student.setMobile(record.getMobile());
		student.setAge(record.getAge());
		student.setName(record.getName());
		
		String userId = studentServerFeign.add(student);
		System.out.println("userId:" + userId);
		customerDao.insertSelective(record);
		return getStudent(userId);
	}
	
	private Integer getStudent(String userId){
		// 查询插入的数据
		if (StringUtils.isBlank(userId)){
			return 0;
		}
		Student newStudent = studentServerFeign.get(Integer.valueOf(userId));
		if (null == newStudent){
			String json = redisUtil.get("feign:" + userId);
			System.out.println("user:" + json);
			newStudent = (Student) JSON.parseObject(json, Student.class);
		}
		System.out.println("name:" + newStudent.getName());
		return newStudent.getId();
	}
	
	@Override
	public Customer selectByPrimaryKey(Integer id) {
		return customerDao.selectByPrimaryKey(id);
	}
	
	@LcnTransaction(propagation = DTXPropagation.REQUIRED) //分布式事务注解(调用方)
	@Transactional(rollbackFor = Exception.class) //本地事务注解
	@Override
	public int updateByPrimaryKeySelective(Customer customer, String name, String mobile) {
		studentServerFeign.update(name, mobile, customer.getId());
		customer.setName(name);
		customer.setMobile(mobile);
//		int a = 1/0;//模拟异常
		return customerDao.updateByPrimaryKeySelective(customer);
	}
	
	@Override
	public int updateByPrimaryKey(Customer record) {
		return customerDao.updateByPrimaryKey(record);
	}
}
